package IO;/*
 *
 * @author 陈粒
 * @version 创建时间：2021/7/16 15:10
 */

import org.junit.Test;

import java.io.*;

/**
 * BufferedReader BufferedWriter：
 * 要读取字符流，只能用BufferedReader，写字符流，只能用BufferedWriter
 */
public class Buffered_Reader_Writer {//复制txt文本

    @Test
    public void testBufferedReader_Writer() {
        File oldfile = new File("C:\\Users\\tarena\\Desktop\\file\\file1.txt");
        File newfile = new File("C:\\Users\\tarena\\Desktop\\file\\file2.txt");
        copyfile_txt(oldfile, newfile);
    }

    public void copyfile_txt(File oldfile, File newfile) {
        //创建Reader、 Writer、BufferedReader、BufferedWriter的成员变量(对象)并赋予初始值
        Reader reader = null;
        Writer writer = null;
        BufferedReader br = null;
        BufferedWriter bw = null;
        try {
            reader = new FileReader(oldfile);//创建字符流对象并赋值
            br = new BufferedReader(reader);//将字符流对象传入到BufferReader构造函数中

            writer = new FileWriter(newfile);//创建字符流对象并赋值
            bw = new BufferedWriter(writer);//将字符流对象传入到BufferWriter构造函数中
            String s = null;
            while ((s = br.readLine()) != null) {//调用readline方法，每次读取一行的内容
                bw.write(s);
                bw.newLine();//换行，s是一行数据，所以每写一行就要换行
            }
            bw.flush();//强制把数组内容写入文件
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}